package com.fyzk.base;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.app.App;
import com.fyzk.activity.app.AppToast;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.interfaces.onTopTitleClickListener;
import com.fyzk.net.PublicMethod;
import com.fyzk.net.ToolsAesCrypt;
import com.fyzk.utils.AppUtil;
import com.fyzk.utils.Base64;
import com.fyzk.utils.LogUtil;
import com.fyzk.utils.LogUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.http.body.RequestBody;
import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import com.wf.domain.UrlDef;

import http.Common.CommandUtil;
import http.DataUtil.md5.MD5;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;
import http.XRequestCallBack;

/**
 * Fragement基类
 *
 * @author miao
 */
public class BaseFragment extends Fragment implements
        OnClickListener, onTopTitleClickListener {

    public final String TAG = this.getClass().getSimpleName();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return super.onCreateView(inflater, container, savedInstanceState);
    }


    /**
     * post请求
     *
     * @param requestCode
     * @param params
     * @param showProgress 是否显示加载提示
     */
    public void httpPostJson(int requestCode, String command, JSONObject params,
                             boolean showProgress) {
        sendRequestUseJson(requestCode, command, params, showProgress);
    }

    /**
     * post请求(返回结果不加密)
     *
     * @param requestCode
     * @param params
     * @param showProgress 是否显示加载提示
     */
    public void httpPostJsonNo(int requestCode, String command, JSONObject params,
                               boolean showProgress, String url) {
        sendRequestJson(requestCode, command, params, showProgress, url);
    }


    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {

    }

    protected void onSuccess(int requestCode, String result) {

    }

    protected void onFailure(int requestCode) {

    }

    protected void onFailure(int requestCode, String message) {
        showToast(message);
    }

    protected void showToast(String str) {
        AppToast.getToast().show(str);
    }

    protected void showToast(int str) {
        AppToast.getToast().show(str);
    }

    Map<String, XRequestCallBack<String>> callBackMap = new HashMap<>();

    /**
     * U粉通接口 使用json请求数据
     *
     * @param requestCode
     * @param params2
     * @param showProgress
     */
    public void sendRequestUseJson(final int requestCode, String command,
                                   JSONObject params2, final boolean showProgress) {
        if (!AppUtil.isNetworkAvailable(getActivity())) {
            AppToast.getToast().show("网络错误!");
            return;
        }

        if (showProgress) {
//            showProgressDialog();
        }

        XRequestCallBack<String> callBack = callBackMap.get(requestCode + "");
        if (callBack == null) {
            callBack = new XRequestCallBack<String>(
                    requestCode) {
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                    onFailure(getRequestCode(), "网络异常");
                    if (showProgress) {
//					cancelProgressDialog();
                    }
                }

                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    String netResult = null;
                    String decode_ = null;
                    try {
                        decode_ = ToolsAesCrypt.Decrypt(requestCode == CommandUtil.GETWINORDER ? result : result.substring(1, result.length() - 1),
                                UrlDef.stringFromJNI());
                        if (requestCode != CommandUtil.GETWINORDER) {
                            System.out.println("decode>" + decode_);
                            byte[] base64d = Base64.decode(decode_);
                            byte[] decompress = PublicMethod.decompress2(base64d);
                            netResult = new String(decompress, "utf-8");
                        } else {
                            netResult = decode_;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    try {
                        StringResultBean resultBean = JSON.parseObject(netResult,
                                StringResultBean.class);
                        LogUtil.d(requestCode + "联网返回成功：" + requestCode + netResult);
                        if (resultBean.getErrorcode().equals("0")) {
                            BaseFragment.this.onSuccess(getRequestCode(), resultBean,
                                    netResult);
                        } else if (resultBean.getErrorcode().equals("110003")) {
                            MySharedPreferences.getInstance().setAuthToken("");
                            MySharedPreferences.getInstance().setLoginStatus(false);
                            onFailure(getRequestCode(), resultBean.getErrorcode(), resultBean.getMsg());
                        } else {
                            onFailure(getRequestCode(), resultBean.getErrorcode(), resultBean.getMsg());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        BaseFragment.this.onFailure(getRequestCode(), "9999",
                                netResult);
                    }
                    if (showProgress) {
//					cancelProgressDialog();
                    }
                }
            };
            callBackMap.put(requestCode + "", callBack);
        }

        RequestParams params = new RequestParams(requestCode == CommandUtil.GETWINORDER ? UrlDef.getZhongjiang : UrlDef.TY_URL_NEW_DATA);
        //打印请求
        try {
            JSONObject requstJson = new JSONObject();
            if (requestCode != CommandUtil.GETWINORDER) {
                JSONObject clientInfo = new JSONObject();
                long timestamp = System.currentTimeMillis();
                String hah = MD5.toMd5((UrlDef.stringFromJNI() + timestamp).getBytes("UTF-8"));
                String token = http.DataUtil.md5.MD5.toMd5(hah.getBytes("UTF-8"));
                LogUtil.d("toke>>>" + token);
                clientInfo.put("agentId", App.getChannel());
                clientInfo.put("apn", "WIFI");
                clientInfo.put("authtoken", MySharedPreferences.getInstance().getAuthtoken());
                clientInfo.put("model", "android");
                clientInfo.put("platform", "android");
                clientInfo.put("timestamp", timestamp);
                clientInfo.put("token", token);
                clientInfo.put("version", App.getVersionName());
                requstJson.put("clientInfo", clientInfo);
                requstJson.put("command", command);
                String branch = MySharedPreferences.getInstance().getBranch();
                String companyid = MySharedPreferences.getInstance().getCompanyid();
                if (TextUtil.isEmpty(branch)) {
                    branch = App.BRANCH;
                    MySharedPreferences.getInstance().setBranch(App.BRANCH);
                }
                if (TextUtil.isEmpty(companyid)) {
                    companyid = App.COMPANYID;
                    MySharedPreferences.getInstance().setCompanyid(App.COMPANYID);
                }
                clientInfo.put("branch", branch);
                clientInfo.put("companyid", companyid);
                if (params2 == null) params2 = new JSONObject();
                params2.put("sysCode", "HM");
                requstJson.put("data", params2);
            } else {
                requstJson.put("command", command);
            }
            LogUtil.d(requestCode + "联网：加密前请求>" + requstJson.toString());
            String encrypt = ToolsAesCrypt.Encrypt(requstJson.toString(), UrlDef.stringFromJNI());
            LogUtil.d(requestCode + "联网：加密后请求>" + encrypt);
            params.setBodyContent("body=" + encrypt);
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.d("加密失败");
        }
        x.http().post(params, callBack);
    }

    /**
     * U粉通接口 使用json请求数据
     *
     * @param requestCode
     * @param method
     * @param params
     * @param showProgress
     */
    public void sendRequest(HttpMethod method, final int requestCode, RequestParams params, final
    boolean showProgress) {
        if (!AppUtil.isNetworkAvailable(getActivity())) {
            AppToast.getToast().show("网络错误!");
            return;
        }
        if (showProgress) {
//			showProgressDialog();
        }
        XRequestCallBack<String> callBack = new XRequestCallBack<String>(
                requestCode) {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
//                onFailure(getRequestCode(), "网络异常");
                LogUtil.d("请求失败");
                BaseFragment.this.onFailure(getRequestCode());
                if (showProgress) {
//					cancelProgressDialog();
                }
            }

            @Override
            public void onSuccess(String result) {
                LogUtil.d("联网返回成功：" + requestCode + result);
                super.onSuccess(result);
                try {
                    StringResultBean resultBean = JSON.parseObject(result,
                            StringResultBean.class);
                    if (resultBean.getErrorcode().equals("0")) {
                        BaseFragment.this.onSuccess(getRequestCode(), resultBean,
                                result);
                    } else {
                        onFailure(getRequestCode(), resultBean.getErrorcode(), resultBean.getMsg());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    BaseFragment.this.onFailure(getRequestCode(), "9999",
                            "数据异常");
                }
                if (showProgress) {
//					cancelProgressDialog();
                }
            }
        };
        LogUtil.v("联网请求：" + params);
        if (method == HttpMethod.POST) {
            x.http().post(params, callBack);
        } else if (method == HttpMethod.GET) {
            x.http().get(params, callBack);
        } else {
            x.http().post(params, callBack);
        }
    }

    /**
     * U粉通接口 使用json请求数据
     *
     * @param requestCode
     * @param method
     * @param params
     */
    public void sendRequestGet(HttpMethod method, int requestCode, RequestParams params) {
        if (!AppUtil.isNetworkAvailable(getActivity())) {
            AppToast.getToast().show("网络错误!");
            return;
        }

        XRequestCallBack<String> callBack = new XRequestCallBack<String>(requestCode) {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                onFailure(getRequestCode(), "网络异常");
            }

            @Override
            public void onSuccess(String result) {
                LogUtil.d("联网返回成功：" + result);
                super.onSuccess(result);
                BaseFragment.this.onSuccess(getRequestCode(), result);
            }
        };

        LogUtil.v("联网请求：" + params);
        if (method == HttpMethod.GET) {
            x.http().get(params, callBack);
        } else {
            x.http().post(params, callBack);
        }
    }

    public void onFailure(int requestCode, String errorcode, String msg) {
        onFailure(requestCode, msg);
    }

    protected void onFailure(StringResultBean resultBean, int requestCode, String errorCode,
                             String message) {
        onFailure(requestCode, errorCode,
                message);
    }

    public void httpPostJsonHead(int requestCode, RequestParams params, boolean showProgress) {
        sendRequestUseJsonHead(requestCode, params, showProgress);
    }

    public void sendRequestUseJsonHead(final int requestCode, RequestParams params, final boolean showProgress) {
        if (!AppUtil.isNetworkAvailable(getActivity())) {
            AppToast.getToast().show("网络错误!");
            return;
        }

        if (showProgress) {
            showProgressDialog();
        }

        XRequestCallBack<String> callBack = callBackMap.get(requestCode + "");
        if (callBack == null) {
            callBack = new XRequestCallBack<String>(
                    requestCode) {
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                    LogUtils.e("====ex toString====" + ex.toString());
                    onFailure(getRequestCode(), "网络异常");
                    if (showProgress) {
                        cancelProgressDialog();
                    }
                }

                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    LogUtils.e("====result pic====" + result);
                    try {
                        StringResultBean resultBean = JSON.parseObject(result,
                                StringResultBean.class);
                        if (resultBean.getErrorcode().equals("0")) {
                            BaseFragment.this.onSuccess(getRequestCode(), resultBean,
                                    result);
                        } else if (resultBean.getErrorcode().equals("110003")) {
                            MySharedPreferences.getInstance().setAuthToken("");
                            MySharedPreferences.getInstance().setLoginStatus(false);
                            onFailure(getRequestCode(), resultBean.getErrorcode(), resultBean.getMsg());
                        } else {
                            onFailure(getRequestCode(), resultBean.getErrorcode(), resultBean.getMsg());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        BaseFragment.this.onFailure(getRequestCode(), "9999",
                                result);
                    }
                    if (showProgress) {
                        cancelProgressDialog();
                    }
                }
            };
            callBackMap.put(requestCode + "", callBack);
        }
        x.http().post(params, callBack);
    }

    /**
     * U粉通接口 使用json请求数据（返回结果没有加密）
     *
     * @param requestCode
     * @param params2
     * @param showProgress
     */
    public void sendRequestJson(final int requestCode, String command,
                                JSONObject params2, final boolean showProgress, String url) {
        if (!AppUtil.isNetworkAvailable(getActivity())) {
            AppToast.getToast().show("网络错误!");
            BaseFragment.this.onFailure(requestCode, "网络错误!");
            return;
        }
        if (showProgress) {
            showProgressDialog();
        }
        XRequestCallBack<String> callBack = callBackMap.get(requestCode + "");
        if (callBack == null) {
            callBack = new XRequestCallBack<String>(requestCode) {
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                    LogUtil.d("联网失败:" + ex.getMessage());
                    BaseFragment.this.onFailure(getRequestCode(), null);
                    if (showProgress) {
                        cancelProgressDialog();
                    }
                }

                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    LogUtil.d("联网返回成功:" + result);
                    if (showProgress) {
                        cancelProgressDialog();
                    }

                    try {
                        if (showProgress) {
                            cancelProgressDialog();
                        }
                        StringResultBean resultBean = JSON.parseObject(result,
                                StringResultBean.class);
                        if (resultBean.getErrorcode().equals("0")) {
                            LogUtil.e("success>>>>>>");
                            BaseFragment.this.onSuccess(getRequestCode(), resultBean,
                                    result);
                        } else if (resultBean.getErrorcode().equals("110003")) {
                            MySharedPreferences.getInstance().setAuthToken("");
                            MySharedPreferences.getInstance().setLoginStatus(false);
                            BaseFragment.this.onFailure(resultBean, getRequestCode(), resultBean
                                    .getErrorcode(), resultBean.getMsg());
                        } else {
                            LogUtil.e("fail>>>>>>");
                            BaseFragment.this.onFailure(resultBean, getRequestCode(), resultBean
                                    .getErrorcode(), resultBean.getMsg());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        if (showProgress) {
                            cancelProgressDialog();
                        }
                        LogUtil.d("BaseActivity >>  result 数据异常。。");
                        StringResultBean bean = null;
                        BaseFragment.this.onSuccess(getRequestCode(), bean,
                                result);
                    }
                    if (showProgress) {
                        cancelProgressDialog();
                    }
                    this.onFinished();

                }
            };
            callBackMap.put(requestCode + "", callBack);
        }


        RequestParams params = new RequestParams(url);
        //打印请求
        try {
            JSONObject requstJson = new JSONObject();

            JSONObject clientInfo = new JSONObject();
            long timestamp = System.currentTimeMillis();


            String token = http.DataUtil.md5.MD5.toMd5(http.DataUtil.md5.MD5.toMd5((UrlDef
                    .stringFromJNI() +
                    timestamp).getBytes()).getBytes());
            clientInfo.put("agentId", App.getChannel());
            clientInfo.put("apn", "WIFI");
            clientInfo.put("authtoken", MySharedPreferences.getInstance().getAuthtoken());
            clientInfo.put("model", "android");
            clientInfo.put("platform", "android");
            clientInfo.put("timestamp", timestamp);
            clientInfo.put("token", token);
            clientInfo.put("version", App.getVersionName());
            String branch = MySharedPreferences.getInstance().getBranch();
            String companyid = MySharedPreferences.getInstance().getCompanyid();
            if (TextUtil.isEmpty(branch)) {
                branch = App.BRANCH;
                MySharedPreferences.getInstance().setBranch(App.BRANCH);
            }
            if (TextUtil.isEmpty(companyid)) {
                companyid = App.COMPANYID;
                MySharedPreferences.getInstance().setCompanyid(App.COMPANYID);
            }
            clientInfo.put("branch", branch);
            clientInfo.put("companyid", companyid);
            requstJson.put("clientInfo", clientInfo);
            requstJson.put("command", command);
            if (params2 == null) params2 = new JSONObject();
            params2.put("sysCode", "HM");
            requstJson.put("data", params2);
            LogUtil.d("联网：加密前请求>" + requstJson.toString());
            String encrypt = ToolsAesCrypt.Encrypt(requstJson.toString(), UrlDef.stringFromJNI());
            LogUtil.d("联网：加密后请求>" + encrypt);
            params.setBodyContent("body=" + encrypt);
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.d("加密失败");
        }

        LogUtil.v("联网请求：" + params);
        x.http().post(params, callBack);

    }

    private ProgressDialog progressDialog;

    public void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getContext());
            progressDialog.setMessage("联网处理中……");
        }
        progressDialog.show();
    }

    protected void cancelProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.cancel();
        }
    }

    @Override
    public void onLeftClick() {
    }

    @Override
    public void onCenterClick() {

    }

    @Override
    public void onRightClick() {

    }

    @Override
    public void onRight2Click() {

    }

    @Override
    public void onClick(View v) {

    }

    public Context getContext() {
        return getActivity();
    }

    /**
     * U粉通接口 使用json请求数据
     *
     * @param requestCode
     * @param params2
     * @param showProgress
     */
    public void sendRequestUseJsonWithProgress(final int requestCode, String command,
                                               JSONObject params2, final boolean showProgress) {
        if (!AppUtil.isNetworkAvailable(getActivity())) {
            AppToast.getToast().show("网络错误!");
            return;
        }

        if (showProgress) {
            showProgressDialog();
        }

        XRequestCallBack<String> callBack = callBackMap.get(requestCode + "");
        if (callBack == null) {
            callBack = new XRequestCallBack<String>(
                    requestCode) {
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                    onFailure(getRequestCode(), "网络异常");
                    if (showProgress) {
                        cancelProgressDialog();
                    }
                }

                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    String netResult = null;
                    String decode_ = null;
                    try {
                        decode_ = ToolsAesCrypt.Decrypt(result.substring(1, result.length() - 1),
                                UrlDef.stringFromJNI());
                        System.out.println("decode>" + decode_);
                        byte[] base64d = Base64.decode(decode_);
                        byte[] decompress = PublicMethod.decompress2(base64d);
                        netResult = new String(decompress, "utf-8");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    try {
                        StringResultBean resultBean = JSON.parseObject(netResult,
                                StringResultBean.class);
                        LogUtil.d("联网返回成功：" + requestCode + netResult);
                        if (resultBean.getErrorcode().equals("0")) {
                            BaseFragment.this.onSuccess(getRequestCode(), resultBean,
                                    netResult);
                        } else if (resultBean.getErrorcode().equals("110003")) {
                            MySharedPreferences.getInstance().setAuthToken("");
                            MySharedPreferences.getInstance().setLoginStatus(false);
                            onFailure(getRequestCode(), resultBean.getErrorcode(), resultBean.getMsg());
                        } else {
                            onFailure(getRequestCode(), resultBean.getErrorcode(), resultBean.getMsg());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        BaseFragment.this.onFailure(getRequestCode(), "9999",
                                netResult);
                    }
                    if (showProgress) {
                        cancelProgressDialog();
                    }
                }
            };
            callBackMap.put(requestCode + "", callBack);
        }

        RequestParams params = new RequestParams(UrlDef.TY_URL_NEW_DATA);
        //打印请求
        try {
            JSONObject requstJson = new JSONObject();

            JSONObject clientInfo = new JSONObject();
            long timestamp = System.currentTimeMillis();
            String hah = MD5.toMd5((UrlDef.stringFromJNI() + timestamp).getBytes("UTF-8"));
            String token = http.DataUtil.md5.MD5.toMd5(hah.getBytes("UTF-8"));
            LogUtil.d("toke>>>" + token);
            clientInfo.put("agentId", App.getChannel());
            clientInfo.put("apn", "WIFI");
            clientInfo.put("authtoken", MySharedPreferences.getInstance().getAuthtoken());
            clientInfo.put("model", "android");
            clientInfo.put("platform", "android");
            clientInfo.put("timestamp", timestamp);
            clientInfo.put("token", token);
            clientInfo.put("version", App.getVersionName());
            requstJson.put("clientInfo", clientInfo);
            requstJson.put("command", command);
            String branch = MySharedPreferences.getInstance().getBranch();
            String companyid = MySharedPreferences.getInstance().getCompanyid();
            if (TextUtil.isEmpty(branch)) {
                branch = App.BRANCH;
                MySharedPreferences.getInstance().setBranch(App.BRANCH);
            }
            if (TextUtil.isEmpty(companyid)) {
                companyid = App.COMPANYID;
                MySharedPreferences.getInstance().setCompanyid(App.COMPANYID);
            }
            clientInfo.put("branch", branch);
            clientInfo.put("companyid", companyid);
            if (params2 == null) params2 = new JSONObject();
            params2.put("sysCode", "HM");
            requstJson.put("data", params2);
            LogUtil.d("联网：加密前请求>" + requstJson.toString());
            String encrypt = ToolsAesCrypt.Encrypt(requstJson.toString(), UrlDef.stringFromJNI());
            LogUtil.d("联网：加密后请求>" + encrypt);
            params.setBodyContent("body=" + encrypt);
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.d("加密失败");
        }
        x.http().post(params, callBack);
    }

}
